// pages/me/secondBatch/secondBatch.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        searchParams:{
            pageNum: 1,
            pageSize: 6,
            queryType:'1',
            pages:'',
            total:'',
        },
        noData: true,
        InitData:false,
        auctionList:{},
        auctionTimer: null,
        scopeRow:{
            index:0
        },
        modalName:null,
        userInfo:{}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    doNothing(){},
    onLoad: function (options) {
        this.InitUserStatus();
        this.setData({
          'InitData': true
        })
    },
    // 检查一下登录状态。
    async InitUserStatus(){
        app.showLoading("获取用户信息");
        await app.checkToken();
        this.InitUserInfo();
        wx.hideLoading();
    },
    InitUserInfo(){
        let userInfo = app.globalData.userInfo;
        // 这里再验证一遍权限。
        if (userInfo.roleList.indexOf('manageAuction') == -1) {
            app.showNoAuthOrNoGrant('您无权操作查看此页面');
            return;
        }else{
          this.setData({
            'userInfo': userInfo
          })
            this.goQuery();
        }
    },
    goQuery(){
      this.setData({
        'searchParams.pageNum':1,
        'searchParams.total':'',
        'searchParams.pages':'',
        'auctionList': {}
      });
      this.auctionSelfList(this.data.searchParams);
    },
    auctionSelfList(searchParams){
      searchParams.queryType == ""? delete searchParams.queryType:'';
      // 整理完成进行搜索操作。
      app.sHttp.auctionSelfList(searchParams).then(res=>{
          let auctionList = this.data.auctionList;
          auctionList[searchParams.pageNum] = res.result.auctionList;
          if (0 == res.result.total) {
            this.setData({
              'noData': true
            })
          }else{
              this.setData({
                  'noData': false,
                  'auctionList': auctionList,
                  'searchParams.total':res.result.total,
                  'searchParams.pages': res.result.pages
                });
                this.handleTimer()
          }
        },err=>{
          app.error(err.msg);
        })
    },
    switchType(e){
        let type = e.currentTarget.dataset.type;
        let _this = this;
        this.setData({
            'searchParams.queryType': type
        },(res)=>{
            _this.goQuery();
        })
    },
    onUnload(){
        if (this.data.auctionTimer) {
            clearInterval(this.data.auctionTimer);
          };
    },
    onReachBottom(){
        if (this.data.searchParams.pageNum == this.data.searchParams.pages) {
            //app.alert('没有更多了哦~');
        }else{
            let self = this;
            this.setData({
                'searchParams.pageNum': self.data.searchParams.pageNum+1
            });
            this.auctionSelfList(this.data.searchParams);
        }
    },     
    // 计算倒计时。
    handleTimer(){
        var that = this
        var auctionList = that.data.auctionList;
        for (const key in auctionList) {
          if (Object.hasOwnProperty.call(auctionList, key)) {
            const element = auctionList[key];
            element.forEach(element => {
              if(element.endTime){
                element.time = that.queryTime(element.endTime);
              }
            });
          }
        }
        this.setData({
          'auctionList': auctionList
        });
        this.setCountDown();
    },
    setCountDown(){
        if (this.data.auctionTimer) {
            clearInterval(this.data.auctionTimer);
          };
          let self = this;
          let auctionTimer = setInterval(() => {
            console.log('我是老二');
            let time = 1000;
            let {
              auctionList
            } = self.data;
            for (const key in auctionList) {
              if (Object.hasOwnProperty.call(auctionList, key)) {
                const element = auctionList[key];
                element.map((v, i) => {
                  if (3 == v.status) {
                    if (v.time <= 0) {
                      v.time = 0;
                    }
                    let formatTime = self.getFormat(v.time);
                    v.time -= time;
                    v.countDownHH = formatTime.hh;
                    v.countDownMM = formatTime.mm;
                    v.countDownSS = formatTime.ss;
                  }
                  return v;
                })
              }
            }
            self.setData({
              'auctionList': auctionList
            });
          }, 1000);
          this.setData({
            'auctionTimer': auctionTimer
          })
    },
    getFormat(msec) {
        let ss = parseInt(msec / 1000);
        let ms = parseInt(msec % 1000);
        let mm = 0;
        let hh = 0;
        if (ss > 60) {
        mm = parseInt(ss / 60);
        ss = parseInt(ss % 60);
        if (mm > 60) {
        hh = parseInt(mm / 60);
        mm = parseInt(mm % 60);
        }
        }
        ss = ss > 9 ? ss : `0${ss}`;
        mm = mm > 9 ? mm : `0${mm}`;
        hh = hh > 9 ? hh : `0${hh}`;
        return { ss, mm, hh };
    },
    queryTime(pintime){
        var start_date = new Date();
        var end_date = new Date(pintime.replace(/-/g, "/"));
        var days = end_date.getTime() - start_date.getTime();
        console.log("获取到时间差" + days)
        return days;
    },
    makePhoneCall(){
        wx.makePhoneCall({
            phoneNumber: app.globalData.customerService,
            success:function(){},
            fail:function(){}
        })
    },
    makePhoneCallSuccess(e){
        let page = e.currentTarget.dataset.page;
        let index = e.currentTarget.dataset.idx;
        let item = this.data.auctionList[page][index];
        if(undefined != item.offerList){
            let phone = item.offerList[0].userMobile
            wx.makePhoneCall({
                phoneNumber: phone,
                success:function(){},
                fail:function(){}
            })
        }
    },
    // 下架结束一口价窗口。
    endSebModal(e){
        let row = null;
        try {
            row = app.deepCopy(this.data.auctionList[e.currentTarget.dataset.page][e.currentTarget.dataset.idx]);
            if(undefined == row.depositList){
              row.depositList = [];
            }
            row.depositList.push({'orderNo':'',userMobile:'没有成交'});
            row.operationPageNum = e.currentTarget.dataset.page;
            row.index = 0;
            if (row) {
                this.setData({
                    'scopeRow': row,
                    'modalName': 'endSeb'
                })
            }
        } catch (error) {
            app.alert('请关闭重试');
            return
        }
    },
    hideModal(e) {
        this.setData({
          'modalName': null,
          'scopeRow':{}
        })
    },
    chooseSebItem(e){
        this.setData({
            'scopeRow.index':e.currentTarget.dataset.idx
        })
    },
    secondBatchSelfClose(){
      let params = {secondBatchId:this.data.scopeRow.secondBatchId};
      let chooseOrder = this.data.scopeRow.depositList[this.data.scopeRow.index];
      if ('' != chooseOrder.orderNo) {
        params.orderSn = chooseOrder.orderNo
      }
      app.sHttp.secondBatchSelfClose(params).then(res=>{
        app.success('处理完成~');
        let self = this;
        setTimeout(() => {
            let searchParams = self.data.searchParams;
            searchParams.pageNum = self.data.scopeRow.operationPageNum;
            self.auctionSelfList(searchParams);
            self.hideModal();
        }, 1000);
      },err=>{
        app.error(err.msg);
      })
    },
})